package codeTop;

/**
 * codeTop.q123
 *
 * @author 雨凡
 * @version codeTop.q123.java, v0.1
 * @date 2025/07/05/09:48
 */
public class q123 {
    //超时
    public int maxProfit1(int[] prices) {
        int max = simpleMaxProfit(prices, 0, prices.length - 1);
        for (int i = 0; i < prices.length - 1; i++) {
            if (prices[i] > prices[i + 1]) {
                max = Math.max(simpleMaxProfit(prices, 0, i) + simpleMaxProfit(prices, i + 1, prices.length - 1), max);
            }
        }
        return max;
    }

    int simpleMaxProfit(int[] prices, int l, int r) {
        if (l >= r) {
            return 0;
        }
        int min = prices[l];
        int res = 0;
        for (int i = l; i <= r; i++) {
            min = Math.min(min, prices[i]);
            res = Math.max(res, prices[i] - min);
        }
        return res;
    }

    public int maxProfit(int[] prices) {
        int min = prices[0];
        int[] arr1 = new int[prices.length];
        int maxNum = 0;
        for (int i = 0; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            maxNum = Math.max(prices[i] - min,maxNum);
            arr1[i] = maxNum;
        }
        int max = prices[prices.length - 1];
        int[] arr2 = new int[prices.length];
        maxNum = 0;
        for (int i = prices.length - 1; i >= 0; i--) {
            max = Math.max(max, prices[i]);
            maxNum = Math.max(max - prices[i],maxNum);
            arr2[i] = maxNum;
        }
        int res = 0;
        for (int i = 0; i < prices.length; i++) {
            res = Math.max(arr1[i] + arr2[i], res);
        }
        return res;
    }
}
